/**
 * Created by apple on 2016/11/28.
 */
var express = require('express');
var router = express.Router();
var Hospitals = require('../models').Hospital;
var Area = require('../models').Area;
var Department = require('../models').Department;
var Doctor = require('../models').Doctor;
var url = require('url');
var querystring = require('querystring');
var utils = require('../utils');
var async = require('async');

/*
 * 医院的列表iframe，将嵌到医院主页面中 */
router.get('/hospital_list_frame', function (req, res, next) {
	var js_object = querystring.parse(url.parse(req.url).query);

	var cid = parseInt(js_object.cid);
	var aid = parseInt(js_object.aid);
	var hl = parseInt(js_object.hl);

	if (isNaN(cid) || isNaN(aid) || isNaN(hl)) {
		res.redirect('/');
	}

	var list_hp = [];

	if (aid !== 0) {
		Hospitals.findByAreaAndLevel(aid, hl).then(function (list_hp_f) {
			list_hp_f.forEach(function (item) {
				list_hp.push(item.dataValues);
			});

			res.render('hospital/hospital_list_frame', {
				hp_list:list_hp
			});
		});
	}
	else {
		//查找cid所对应的市的所有医院
		Hospitals.findByCityAndLevel(cid, hl).then(function (list_hp_f) {
			list_hp_f.forEach(function (item) {
				list_hp.push(item.dataValues);
			});

			res.render('hospital/hospital_list_frame', {
				hp_list: list_hp.sort(function (a, b) {
					return (a.id > b.id);
				})
			});
		});
	}

});

/*
 * hospital main page which contains area selectors and hospital list */
router.get('/', function (req, res, next) {
	var list_city = [];
	var list_area = [];

	//默认的地区：北京、北京市、海淀区
	var pid = 2, cid = 52, aid = 502, hl = 0;

	var hp_url = '';

	var loca = req.session.location;
	//根据session中的信息更新地区信息
	if (loca != undefined && loca.pid != undefined && loca.cid != undefined && loca.aid != undefined) {
		pid = loca.pid;
		cid = loca.cid;
		aid = loca.aid;
	}
	else {//根据将当前地区信息更新session
		utils.locationSession(req, res, pid, cid, aid);
        loca = req.session.location;
	}

	//在get时,地区信息应当是合法的
    Area.findByPid(pid).then(function (list_city_f) {
	    list_city = list_city_f;
	    return Area.findByPid(cid);
    }).then(function (list_area_f) {
	    list_area = list_area_f;

	    hp_url = '/hospital/hospital_list_frame?pid=' + pid + '&cid=' + cid + '&aid=' + aid + '&hl=' + hl;

	    res.render('hospital/find_hospital', {
	    	title: '找医院',
		    user: req.session.user,
		    city: list_city,
		    area: list_area,
		    location:loca,
		    hp_list_url: hp_url
	    });
    });
}).post('/', function (req, res, next) {

	var pid = parseInt(req.body.p_id);        //省/直辖市的id
	var cid = parseInt(req.body.c_id);        //市的id
	var aid = parseInt(req.body.a_id);        //区\县的id
	var hl = parseInt(req.body.h_level);      //医院级别

	var list_city = [];
	var list_area = [];
	//var list_hp = [];

	var hp_url = '';

	var capital_id;
	Area.findByPid(pid).then(function (list_city_f) {//得到当前省份所有市的列表，并将首府设为该表的第一个城市
		list_city = list_city_f;
		capital_id = parseInt(list_city[0].dataValues.area_id);

		return Area.findById(cid);
	}).then(function (city_f) {//如果当前城市所在的省不是当前省，则将当前城市设为当前省的首府
		var parent_id = parseInt(city_f.get("parent_id"));
		if (parent_id !== pid) {
			cid = capital_id;
		}

		return Area.findByPid(cid);
	}).then(function (list_area_f) {//得到当前市的所有地区的列表，并通过aid查找当前地区，如果aid为0，则返回null
		list_area = list_area_f;
		return Area.findById(aid);
	}).then(function (area_f) {//如果当前地区所在的市，如果不是当前市，则将当前地区设为0，意为当前市的所有地区
		if (area_f !== null) {
			var parent_id = parseInt(area_f.parent_id);
			if (parent_id !== cid) {
				aid = 0;
			}
		}
		//如果aid为0，则查找到当前市的所有医院，如果aid不为0，则查找当前地区的所有医院
		var city_json = [];
		var area_json = [];

		//将所有列表转为json格式发送
		list_city.forEach(function (item) {
			city_json.push(item.dataValues);
		});

		list_area.forEach(function (item) {
			area_json.push(item.dataValues);
		});

		//将当前地区信息放入session
		utils.locationSession(req, res, pid, cid, aid);

		//向子页面传递新的url
		hp_url = '/hospital/hospital_list_frame?pid=' + pid + '&cid=' + cid + '&aid=' + aid + '&hl=' + hl;
		res.json({
			user: req.session.user,
			city: city_json,
			area: area_json,
			hp_list_url:hp_url
		});
	});
});

router.get('/details', function (req, res, next) {

	var hp_id = parseInt(querystring.parse(url.parse(req.url).query).hp_id);
	var hp;
	var fid = -1, sid = 0, dl = 0;
	var list_dept_f = [];
	var list_dept_s = [];

	if (isNaN(hp_id)) {
		res.redirect('/');
	}

	var dept = req.session.department;

	//根据session中的信息更新fid或者根据当前信息更新session
	//将所得的信息发送回浏览器
	if (dept !== undefined &&
		dept.hospital !== undefined && dept.hospital.id == hp_id &&
		dept.list_dept_f !== undefined && dept.list_dept_s !== undefined &&
		dept.first_level !== undefined && dept.second_level !== undefined) {
		list_dept_f = dept.list_dept_f;
		list_dept_s = dept.list_dept_s;
		fid = dept.first_level;
		sid = dept.second_level;
		hp = dept.hospital;

		//向子页面传递的url
		var doc_url = '/doctor/doctor_list_frame?hid=' + hp_id + '&fid=' + fid + '&sid=' + sid + '&dl=' + dl;

		res.render('hospital/hospital_detail', {
			title: '详细信息',
			user: req.session.user,
			hospital: hp,
			dept_f:list_dept_f,
			dept_s: list_dept_s,
			dept: {
				first_level:dept.first_level,
				second_level:dept.second_level
			},
			doc_list_url: doc_url
		});
	}
	else {
		async.waterfall([
			function (callback) {
				Department.findByPid(0).then(function (list_dept_f_f) {//对于每个一级科室，查找其是否有医生，如果有则将该科室加入一级科室列表
					async.each(list_dept_f_f, function (item_f, callback) {
						//如果该一级科室存在doctor
						Doctor.findByHospitalFD(hp_id, item_f.dataValues.id, 0).then(function (doctor_list_f) {
							if (doctor_list_f.length != 0) {
								list_dept_f.push(item_f.dataValues);
							}
							callback(null);
						});
					}, function (err, result) {
						callback(null, list_dept_f);
					});
				});
			},
			function (list_dept_f, callback) {
				fid = list_dept_f[0].id;
				Department.findByPid(fid).then(function (list_dept_s_f) {
					callback(null, list_dept_s_f);
				});
			},
			function (list_dept_s_f, callback) {
				list_dept_s_f.forEach(function (item_s) {//对于每个二级科室，查找其是否有医生，如果有则将该科室加入二级科室列表
					//如果二级科室存在doctor
					Doctor.findByHospitalSD(hp_id, item_s.dataValues.id, 0).then(function (doctor_list_f) {
						if (doctor_list_f.length != 0) {
							list_dept_s.push(item_s.dataValues);
						}
						if (item_s.dataValues.id == list_dept_s_f[list_dept_s_f.length-1].dataValues.id) {
							sid = 0;
							Hospitals.findById(hp_id).then(function (hp_f) {
								callback(null, hp_f);
							});
						}
					});
				});
			},
			function (hp_f, callback) {
				hp = hp_f;

				//将医院和科室信息存在session里以备使用
				utils.departmentSession(req, res, hp, list_dept_f, fid, sid);

				//向子页面传递的url
				var doc_url = '/doctor/doctor_list_frame?hid=' + hp_id + '&fid=' + fid + '&sid=' + sid + '&dl=' + dl;

				res.render('hospital/hospital_detail', {
					title: '详细信息',
					user: req.session.user,
					hospital: hp,
					dept_f: list_dept_f,
					dept_s: list_dept_s,
					dept: dept,
					doc_list_url: doc_url
				});
			}
		], function (err, result) {

		});
	}
}).post('/details', function (req, res, next) {

	var fid = parseInt(req.body.f_id);        //一级科室的id
	var sid = parseInt(req.body.s_id);        //二级科室的id
	var dl = parseInt(req.body.d_level);        //医生级别
	var hid = parseInt(req.session.department.hospital.id);     //医院的id,从session中查找

	//先从session中查找数据，如果数据有变化再重新从数据库中查找
	var dept = req.session.department;

	var list_dept_f = dept.list_dept_f;
	var list_dept_s = [];


	if (fid != dept.first_level) {//如果一级科室发生变化，则更新二级科室列表
		sid = 0;
		Department.findByPid(fid).then(function (list_dept_s_f) {
			async.each(list_dept_s_f, function (item_s, callback) {
				//如果二级科室存在doctor
				Doctor.findByHospitalSD(hid, item_s.dataValues.id, 0).then(function (doctor_list_f) {
					if (doctor_list_f.length != 0) {
						list_dept_s.push(item_s.dataValues);
					}
					callback(null);
				});
			}, function (err, result) {
				//根据当前信息更新session
				utils.departmentSession(req, res, dept.hospital, list_dept_f, list_dept_s, fid, sid);

				//向子页面传递的url
				var doc_url = '/doctor/doctor_list_frame?hid=' + hid + '&fid=' + fid + '&sid=' + sid + '&dl=' + dl;

				res.json({
					user: req.session.user,
					dept_s: list_dept_s,
					doc_list_url: doc_url
				});
			});
		});
	}
	else { //如果一级科室选项都没有变化，则直接使用session里的二级科室列表
		list_dept_s = dept.list_dept_s;

		//向子页面传递的url
		var doc_url = '/doctor/doctor_list_frame?hid=' + hid + '&fid=' + fid + '&sid=' + sid + '&dl=' + dl;

		res.json({
			user: req.session.user,
			dept_s: list_dept_s,
			doc_list_url: doc_url
		});
	}
});

module.exports = router;